package lhy.orm.dao;

import lhy.AppStart;
import lhy.lhyorm.jdbc.JdbcConnectionSource;
import lhy.lhyorm.support.ConnectionSource;
import lhy.utils.PropertyUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

public class DatabaseConnector {
    private static String driver=null;
    private static String url=null;
    private static String username=null;
    private static String password=null;

    //数据库重连时间，1分钟重连一次
    private static final long DB_RECONN_MILLS=1*60*1000;
    static
    {
        try
        {

            Properties prop=PropertyUtils.loadProps("database.properties");
            driver=prop.getProperty("driver");
            url=prop.getProperty("url");
            username=prop.getProperty("username");
            password=prop.getProperty("password");

            Class.forName(driver);
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            AppStart.LOGGER.info("正在注册数据库");
        }catch(Exception e){
            e.printStackTrace();
            AppStart.LOGGER.error("无法注册数据库！");
        }

        new Timer("db_conn").schedule(new TimerTask() {
            @Override
            public void run() {
                AppStart.LOGGER.info("正在重连数据库");
                try {
                    preparedStatement("select 1").executeQuery();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        },0,DB_RECONN_MILLS);
    }
    private static ConnectionSource connectionSource ;
    public static ConnectionSource getConnectionSource(){
        if(connectionSource==null) {
            try {
                connectionSource= new JdbcConnectionSource(url,username,password);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return connectionSource;
    }
    private static Connection connection=null;
    public static Connection getConnection(){
        if(connection==null) {
            connect();
        }
        return connection;
    }
    public static PreparedStatement preparedStatement(String sql){
        try {
            AppStart.LOGGER.info(sql);
            return getConnection().prepareStatement(sql);
        } catch (SQLException e) {
            connect();
            try {
                return getConnection().prepareStatement(sql);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    private static void connect(){
        try {
            connection=DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
            AppStart.LOGGER.error("无法重连数据库！");
        }
    }

}
